package com.travel.interceptor;

import com.travel.mapper.log.ApiLogMapper;
import com.travel.model.entity.log.ApiLog;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
//api日志拦截器 记录api请求和响应日志  
@Component
@RequiredArgsConstructor
public class ApiLogInterceptor implements HandlerInterceptor {

    private final ApiLogMapper apiLogMapper;
    private final ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        startTime.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        try {
            // 创建日志记录
            ApiLog log = new ApiLog();
            log.setPath(request.getRequestURI());
            log.setMethod(request.getMethod());
            log.setRequestTime(LocalDateTime.now());
            log.setStatusCode(response.getStatus());
            log.setClientIp(request.getRemoteAddr());
            log.setUserAgent(request.getHeader("User-Agent"));
            
            // 计算响应时间
            Long start = startTime.get();
            if (start != null) {
                log.setResponseTime(System.currentTimeMillis() - start);
            }
            
            // 保存日志
            apiLogMapper.insert(log);
        } finally {
            startTime.remove();
        }
    }
} 